'use strict';

/* Controllers */   		


function dashboardCtrl($scope,$http,$location) {
	var currentStatus = "online";
	var messageStatus = { "init": 1, "replying": 2};
	
	// Get a reference to the presence data in Firebase.
	var userListRef = new Firebase("https://adviseme.firebaseio.com/");

	var months = {0:"Jan", 1:"Feb", 2:"Mar", 3:"Apr", 4:"May", 5:"Jun",6:"Jul", 7:"Aug", 8:"Sep", 9:"Oct", 10:"Nov",11:"Dec" };
//	Generate a reference to a new location for my user with push.

	var connectedRef = new Firebase("http://adviseme.firebaseio.com/.info/connected");
	document.onIdle = function () {
		setUserStatus("idle");
	};
	document.onAway = function () {
		setUserStatus("away");
	};
	document.onBack = function (isIdle, isAway) {
		setUserStatus("online");
	};

	function setUserStatus(status) {
		// Set our status in the list of online users.
		currentStatus = status;
		//myUserRef.set({ name: $scope.user.id, status: status });
	}


	

	$scope.selectedOptions = [];
	$http.get('fetchExpertTalks').success(function(data) {
		for(var i = 0; i < data.length; i++) {
			data[i].startTime=new Date(data[i].startTime);
			data[i].startDate = data[i].startTime.getDate();
			data[i].startMonth = months[data[i].startTime.getMonth()];
			data[i].startHour = data[i].startTime.getHours()+":"+data[i].startTime.getMinutes();
		}
		$scope.notifications = data;
	});
	
	$http.get('favorites').success(function(data) {
		$scope.favorites = data;
	});
		
	$http.get('myprofile').success(function(data) {
		$scope.user = data;
		
		var myUserRef = userListRef.child($scope.user.id);    
		myUserRef.on("value", function(snapshot) {
			var message = snapshot.val();
			console.log("message is " + message);
			$http.get('message').success(function(data) {
				for(var i = 0; i < data.length; i++) {
					data[i].state = messageStatus.init;
					if(data[i].counselRequestDTO != null) {
						data[i].startTime=new Date(data[i].counselRequestDTO.startTime);
						data[i].startDate = data[i].startTime.getDate();
						data[i].startMonth = months[data[i].startTime.getMonth()];
						data[i].startHour = data[i].startTime.getHours()+":"+data[i].startTime.getMinutes();
					}else {
						data[i].prettyDate = "";
						if(data[i].creationTime != null) {
							data[i].prettyDate = millisecondsToStr(data[i].creationTime);
						}
					}
				}
				$scope.messages = data;
			});
		});

		connectedRef.on("value", function(isOnline) {
			if (isOnline.val()) {
				// If we lose our internet connection, we want ourselves removed from the list.
				myUserRef.onDisconnect().remove();
				// Set our initial online status.
				setUserStatus("online");
			} else {
				// We need to catch anytime we are marked as offline and then set the correct status. We
				// could be marked as offline 1) on page load or 2) when we lose our internet connection
				// temporarily.
				setUserStatus(currentStatus);
			}
		});
	});

	//$scope.stats.userBase=1000;
	//$scope.stats.advisesDelivered=100;
	//$scope.stats.noOfExperts=20;
	$http.get('stats').success(function(data) {
		$scope.stats = data;
	});

	$http.get('pendingRequests').success(function(data) {
		
		
		$scope.pendingRequests = data;
		
	});

/*	$http.get('coupons').success(function(data) {
		$scope.coupons = data;
	});
*/

	$http.get('message').success(function(data) {
		for(var i = 0; i < data.length; i++) {
			data[i].state = messageStatus.init;
			if(data[i].counselRequestDTO != null) {
				data[i].startTime=new Date(data[i].counselRequestDTO.startTime);
				data[i].startDate = data[i].startTime.getDate();
				data[i].startMonth = months[data[i].startTime.getMonth()];
				data[i].startHour = data[i].startTime.getHours()+":"+data[i].startTime.getMinutes();
			} else {
				data[i].prettyDate = "";
				if(data[i].creationTime != null) {
					data[i].prettyDate = millisecondsToStr(data[i].creationTime);
				}
			}
		}
		$scope.messages = data;
	});


	$scope.acceptMessageCounselRequest=function(requestIdIndex){
		var message = $scope.messages[requestIdIndex];
		var myUserRef = userListRef.child(message.fromUser.id);    

		$http.get('counsel/'+message.invitationId+'/Approve').success(function(data) {
			data = eval(data);
			myUserRef.set({ message: "Accept"});
			if(data=="success"){
				$('#msg'+message.id).remove();
			}
			//scope.$apply();
		});
	};

	$scope.rejectMessageCounselRequest=function(requestIdIndex){
		var message = $scope.messages[requestIdIndex];
		var myUserRef = userListRef.child(message.fromUser.id);
		$http.get('counsel/'+message.invitationId+'/Reject').success(function(data) {
			data = eval(data);
			if(data=="success"){
				myUserRef.set({ message: "Reject"});
				$('#msg'+message.id).remove();
			}
			//scope.$apply();
		});
	};	

	$scope.showGenerate = function(){
		return !(nexus.headerScope.notLogin);        
	}; 

	$scope.acceptCounselRequest=function(requestIdIndex){
		var pendingRequest = $scope.pendingRequests[requestIdIndex];

		$http.get('counsel/'+pendingRequest.id+'/Approve').success(function(data) {
			data = eval(data);
			if(data=="success"){
				$('#pr'+pendingRequest.id).remove();
			}
		});
	};

	$scope.rejectCounselRequest=function(requestIdIndex){
		var pendingRequest = $scope.pendingRequests[requestIdIndex];

		$http.get('counsel/'+pendingRequest.id+'/Reject').success(function(data) {
			data = eval(data);
			if(data=="success"){
				$('#pr'+pendingRequest.id).remove();
			}
		});
	};
	
	$scope.acceptExpertTalkRequest=function(requestIdIndex){
		var expertTalk = $scope.notifications[requestIdIndex];

		$http.get('experttalk/'+expertTalk.id+'/Approve').success(function(data) {
			data = eval(data);
			if(data=="success"){
				$('#pr'+expertTalk.id).remove();
			}
		});
	};
	


	$scope.showGenerate = function(){
		return !(nexus.headerScope.notLogin);        
	}; 

/*	var categories = [];

	$http.get('category').success(function(data) {
		$.each(data, function (i, cat) {
			categories.push(cat.name);
		});
	});

	$scope.options = {
			tags: categories
	};

	$scope.newSkill = "";
	
	$scope.updateSkill = function (){
		var reqData = $scope.user;
		reqData.categories.push($scope.newSkill);
		var updatedUser = angular.toJson(reqData);
		$http.post('updateProfile', updatedUser).success(function(data) {
			
			$scope.newSkill = "";
		});	
	};*/
	
	$scope.replyMessage = function(index) {
		$scope.messages[index]['state'] = messageStatus.replying;
		//$scope.$apply();
	};
	
	$scope.newMsg = {value:''};
	
	$scope.sendMessage = function (event, index){
		var reqData = {"message" : $scope.newMsg.value, "toUser":{"id":$scope.messages[index].fromUser.id}};
		var userListRef = new Firebase("https://adviseme.firebaseio.com/");
		var myUserRef = userListRef.child($scope.messages[index].fromUser.id);
		 
		$http.post('message', reqData).success(function(data) {
			$scope.messages[index].state = messageStatus.init;
			 myUserRef.set({ message: $scope.newMsg.value});
			 $scope.newMsg.value = '';
			 alert("Message Posting "+data);
			 $scope.$apply();
			//$location.path('/dashboard');
		}); 
	};
	
	$scope.isInit = function(index) {
		if ($scope.messages[index]['state'] == messageStatus.init) return true;
		return false;
	};
	
	//$location.url('/dashboard/feed');

}

dashboardCtrl.$inject = ['$scope','$http', '$location'];//inject required

function millisecondsToStr (milliseconds) {
    // TIP: to find current time in milliseconds, use:
     var  current_time_milliseconds = new Date().getTime();

    // This function does not deal with leap years, however,
    // it should not be an issue because the output is aproximated.
	milliseconds =  current_time_milliseconds - milliseconds;
	if(milliseconds < 0) milliseconds *= -1;
    function numberEnding (number) { //todo: replace with a wiser code
        return (number > 1) ? 's' : '';
    }

    var temp = Math.floor(milliseconds / 1000);
    var years = Math.floor(temp / 31536000);
    if (years) {
        return years + ' year' + numberEnding(years);
    }
    var days = Math.floor((temp %= 31536000) / 86400);
    if (days) {
        return days + ' day' + numberEnding(days);
    }
    var hours = Math.floor((temp %= 86400) / 3600);
    if (hours) {
        return hours + ' hour' + numberEnding(hours);
    }
    var minutes = Math.floor((temp %= 3600) / 60);
    if (minutes) {
        return minutes + ' minute' + numberEnding(minutes);
    }
    var seconds = temp % 60;
    if (seconds) {
        return seconds + ' second' + numberEnding(seconds);
    }
    return 'less then a second'; //'just now' //or other string you like;
}


function sessionCtrl($scope, $http, $location) {

	$http.get('requests').success(function(data) {
		data=eval(data);
		var startTime = '';
		if(data[0] != undefined && data[0].hasOwnProperty('startTime')){
			startTime = new Date(data[0].startTime);
		}
		
		$scope.currentTime = new Date().getTime();
		$scope.requestReferences = {};
		$scope.requests = data;
		for(var i = 0; i < $scope.requests.length; i++) {
			var startUTCTime = new Date($scope.requests[i].startTime).getTime();
			var endUTCTime = new Date($scope.requests[i].endTime).getTime();
			$scope.requestReferences[$scope.requests[i].id] = i;
			if($scope.requests[i].sessionStatus == "PENDINGAPPROVAL") {
				$scope.requests[i].isDisabled = true;
				$scope.requests[i].buttonText = "Waiting";
			} else if($scope.currentTime > $scope.requests[i].startTime && $scope.currentTime < $scope.requests[i].endTime){
				if($scope.requests[i].expert) {
					$scope.requests[i].isDisabled = false;
					$scope.requests[i].buttonText = "Start";
				} else {
					var sessionState=new Firebase('https://adviseme.firebaseio.com/counselSessions/'+$scope.requests[i].id+'/state');
					$scope.requests[i].isDisabled = true;
					var callback = function(snapshot) {
						 
						 
						  if(snapshot.val()){
							  console.log('session state is ' +snapshot.val().curSessionId+' '+snapshot.val().curState);
						  if(snapshot.val().curState == 0 || snapshot.val().curState == 1) {
							  if(snapshot.val().curSessionId){
								  $scope.requests[$scope.requestReferences[snapshot.val().curSessionId]].isDisabled = false;
							  }
						  } else {
							  if(snapshot.val().curSessionId){
								  $scope.requests[$scope.requestReferences[snapshot.val().curSessionId]].isDisabled = true;
							  }
						  }
						  $scope.$apply();
						}
					};
					sessionState.on('value', callback);
					$scope.requests[i].buttonText = "Join";
				}
			} else {
				$scope.requests[i].isDisabled = true;
				$scope.requests[i].buttonText = millisecondsToStr($scope.requests[i].startTime);
			}	
			
		}
		
	});
	

	$scope.sessionStart = function (sessionId, isExpert){
		if(!$scope.requests[$scope.requestReferences[sessionId]].isDisabled){
		console.log(sessionId);
		var sessionState=new Firebase('https://adviseme.firebaseio.com/counselSessions/'+sessionId+'/state');
		if(isExpert) {
			sessionState.set({curState:0,curSessionId:sessionId});
		} else {
			sessionState.set({curState:1,curSessionId:sessionId});
		}
		//$location.url('dashboard');
		$location.url('/user/'+sessionId+'/startCounsel');
		}
	};
	
}

sessionCtrl.$inject = ['$scope','$http','$location'];//inject required

function AlertDemoCtrl($scope) {
	  $scope.alerts = [
	    { type: 'error', msg: 'Oh snap! Change a few things up and try submitting again.' }, 
	    { type: 'success', msg: 'Well done! You successfully read this important alert message.' }
	  ];

	  $scope.addAlert = function() {
	    $scope.alerts.push({msg: "Another alert!"});
	  };

	  $scope.closeAlert = function(index) {
	    $scope.alerts.splice(index, 1);
	  };

	}

function generateCouponCtrl($scope, $stateParams,$location, $http) {

	$scope.generateCoupon=function(){


		var reqData = {"description" : $('#message').val(), "startTime": $('#datetimepicker1').data('datetimepicker').getDate(), "endTime": $('#datetimepicker2').data('datetimepicker').getDate(), "count":$('#count').val()};
		$http.post('coupon/generateCoupon', reqData).success(function(data) {
			$location.path('/dashboard');
		});

	};

}

generateCouponCtrl.$inject = ['$scope','$stateParams','$location','$http'];//inject required


